from django.contrib import admin
from . import models
from celery_tasks.html.tasks import generate_static_list_search_html,generate_static_sku_detail_html

# Register your models here.


class GoodsCategoryAdmin(admin.ModelAdmin):
    """商品类别模型站点管理类"""
    # 子类重写父类中的方法
    def save_model(self, request, obj, form, change):
        """
        当点击admin中的保存按钮时 会调用此方法
        :param request: 本次保存本次时请求对象
        :param obj: 本次要保持的模型对象
        :param form: admin中表单
        :param change: 是否改变
        """


        obj.save()
        # 重新生成新的列表静态页面
        generate_static_list_search_html.delay()


    def delete_model(self, request, obj):
        """当点击admin中删除按钮时 会调用此方法"""
        obj.delete()
        generate_static_list_search_html.delay()

# @admin.register(models.SKU)
class SKUAdmin(admin.ModelAdmin):
    """商品模型站点管理类"""
    def save_model(self, request, obj, form, change):
        obj.save()
        generate_static_sku_detail_html.delay(obj.id)


class SKUImageAdmin(admin.ModelAdmin):
    """商品图片模型站点管理类"""

    def save_model(self, request, obj, form, change):
        """

        :param request:
        :param obj: 图片模型对象
        :param form:
        :param change:
        :return:
        """
        obj.save()
        sku = obj.sku #通过外键获取图片模型对象所关联的sku模型的id
        #如果当前sku商品还没有默认图片，给它设置一张默认图片
        if not sku.default_image_url:
            sku.default_image_url = obj.image.url
            print(f'{sku.default_image_url},{sku.default_image_url},{sku.id}')
            sku.save()
            generate_static_sku_detail_html.delay(sku.id)

    def delete_model(self, request, obj):
        obj.delete()
        sku = obj.sku
        generate_static_sku_detail_html.delay(sku.id)


admin.site.register(models.GoodsCategory, GoodsCategoryAdmin)
admin.site.register(models.GoodsChannel)
admin.site.register(models.Goods)
admin.site.register(models.Brand)
admin.site.register(models.GoodsSpecification)
admin.site.register(models.SpecificationOption)
admin.site.register(models.SKU, SKUAdmin)
admin.site.register(models.SKUSpecification)
admin.site.register(models.SKUImage, SKUImageAdmin)